<template>
  <a-modal
    title="编辑试卷信息"
    :destroyOnClose="true"
    :maskClosable="false"
    :keyboard="false"
    v-model:visible="visible"
    @ok="handleOk"
  >
    <a-spin :spinning="spinning">
      <a-form ref="formRef" :model="formState" :rules="rules" layout="vertical">
        <a-form-item label="试卷ID">
          <a-input v-model:value="formState.id" disabled style="width: 100%" />
        </a-form-item>
        <a-form-item label="试卷名称" name="name">
          <a-input v-model:value="formState.name" />
        </a-form-item>
        <a-form-item label="试卷说明" name="caption">
          <a-input v-model:value="formState.caption" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { defineComponent, toRefs, ref, watch } from "vue";
import { editOrAddPaper, getPaperInfo } from "../../utils/api";
import { message } from "ant-design-vue";

export default defineComponent({
  props: {
    data: Object,
  },
  setup(props, ctx) {
    const { visible, paperId } = toRefs(props.data);
    const paperList = ref([]);
    const formRef = ref();
    const formState = ref();
    const spinning = ref(false);
    const rules = {
      name: [{ required: true, message: "请输入试卷名称", trigger: "blur" }],
      caption: [{ required: true, message: "请输入试卷说明", trigger: "blur" }],
    };

    const handleOk = () => {
      formRef.value
        .validate()
        .then(() => {
          editOrAddPaper(formState.value).then((res) => {
            message.success(res.data.message);
            visible.value = false;
            ctx.emit("editFinish");
          });
        })
        .catch((error) => {
          console.log("error", error);
        });
    };

    watch(visible, (value) => {
      if (!value) {
        return;
      }

      formState.value = {
        id: -1,
        name: "",
        caption: "",
      };
      if (paperId.value != -1) {
        spinning.value = true;
        getPaperInfo(paperId.value).then((res) => {
          formState.value = res.data.data;
          spinning.value = false;
        });
      }
    });

    return {
      formRef,
      formState,
      paperList,
      visible,
      spinning,
      rules,
      handleOk,
    };
  },
});
</script>
